package cc.yiueil.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
public class JwtUtils {
    private static final String SECRET_KEY = "8353C401-0DC5-4F33-BB47-D4127B2DF31C"; // 秘密字符串
    private static final byte[] KEY_BYTES = SECRET_KEY.getBytes(StandardCharsets.UTF_8);

    /**
     * 生成JWT-Token
     * @param headers
     * @param claims
     * @return
     */
    public static String generateToken(Map<String, Object> headers, Map<String, Object> claims) {
        try {
            JWTCreator.Builder builder = JWT.create();
            builder.withHeader(headers);
            claims.forEach((k, v) -> builder.withClaim(k, v.toString()));
            return builder.sign(Algorithm.HMAC256(KEY_BYTES));
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate JWT token", e);
        }
    }

    /**
     * 校验JWT-Token
     * @param token
     * @return
     */
    public static boolean validateToken(String token) {
        try {
            JWT.require(Algorithm.HMAC256(KEY_BYTES))
                    .build()
                    .verify(token);
            return true;
        } catch (Exception e) {
            log.debug("Failed to validate JWT token", e);
            return false;
        }
    }

    /**
     * 解析JWT-Token
     * @param token
     * @return
     */
    public static DecodedJWT decodedJWT(String token) {
        return JWT.decode(token);
    }
}
